<template>
    <yh-dialog
        :visible.sync="visibleTemp"
        v-bind="$attrs"
        title="调整方案"
        :modal="false"
        :close-on-click-modal="false"
        drag
        zoomable
        width="40vw"
        @close="handleCloseDialog"
    >
        <div class="dialog-main">
            <div class="table">
                <el-row>
                    <el-col :span="5">事件编号</el-col>
                    <el-col :span="7">
                        {{ submitForm.overrunEventId }}
                        <!-- <el-input v-model="submitForm.overrunEventId" disabled size="mini"></el-input> -->
                    </el-col>
                    <el-col :span="5">产品代码/名称</el-col>
                    <el-col :span="7">
                        {{ formatDictFundCodes(submitForm.dictFundCodes) }}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">估值日期</el-col>
                    <el-col :span="7">
                        {{ submitForm.tradeDate }}
                    </el-col>
                    <el-col :span="5">首次超限日期</el-col>
                    <el-col :span="7" style="color: #dd2826">
                        {{ submitForm.ctDate }}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">控制阈值</el-col>
                    <el-col :span="7">
                        {{ submitForm.thresholdValue }}
                    </el-col>
                    <el-col :span="5">计算值</el-col>
                    <el-col :span="7">
                        {{ submitForm.result }}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">连续超限天数</el-col>
                    <el-col :span="7">
                        <el-tag size="mini" :class="handleTagStyle(submitForm.prohibitionDate)">
                            {{ submitForm.prohibitionDate || submitForm.prohibitionDate === 0 ? submitForm.prohibitionDate : '--' }}</el-tag
                        >
                    </el-col>
                    <el-col :span="5">超限调整天数</el-col>
                    <el-col :span="7">
                        <el-tag size="mini" class="tag4">
                            {{ submitForm.insideDays || submitForm.insideDays === 0 ? submitForm.insideDays : '--' }}</el-tag
                        >
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">条款来源</el-col>
                    <el-col :span="19">
                        {{ submitForm.articeInfo || '--' }}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">条款原文</el-col>
                    <el-col :span="19">
                        {{ submitForm.clauseCode || '--' }}
                    </el-col>
                </el-row>
                <el-row class="textarea">
                    <el-col :span="5">调整方案</el-col>
                    <el-col :span="19">
                        <el-input v-model="feedbackName" :disabled="type === 'look'" type="textarea" :rows="3" placeholder="请填写处置方案描述">
                        </el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">
                        <div style="display: flex">
                            <el-upload
                                :multiple="true"
                                :action="actionUrl"
                                :headers="headerObj"
                                :with-credentials="true"
                                list-type="text"
                                :show-file-list="false"
                                :disabled="type === 'look'"
                                :before-upload="beforeAvatarUpload"
                                :on-success="
                                    (res, file, fileList) => {
                                        return uploadFileSuccess(res, file, fileList, '执行标准');
                                    }
                                "
                                :on-error="
                                    (res, file, fileList) => {
                                        return uploadFileError(res, file, fileList, '执行标准');
                                    }
                                "
                            >
                                <el-button :disabled="type === 'look'" size="small" icon="el-icon-plus" style="border: none">添加附件</el-button>
                            </el-upload>
                        </div>
                    </el-col>
                    <el-col :span="19">
                        <UploadFileShow
                            :fileList="fileList1"
                            :type="type"
                            @emitDownLoadFile="downLoadFileBtn"
                            @emitConfirmDelFile="confirmDelFile1"
                        ></UploadFileShow>
                    </el-col>
                </el-row>
            </div>
            <div>
                <p class="title">历史反馈意见</p>
                <RiskTable
                    ref="risk-table2"
                    :tableData="tableData"
                    :tableConfig="tableConfig"
                    :column="columns"
                    :paging="paging"
                    v-loading="tableLoading"
                    style="height: 290px"
                    @page-change="getFeedbackList"
                >
                    <template #fileName="{ row }">
                        <span v-for="(item, index) in row.fileName" :key="index" @click="handleCellFile(item, row.fileCode[index])">
                            <a href="javascript:;">{{ item }}</a>
                        </span>
                    </template>
                </RiskTable>
            </div>
        </div>
        <div slot="footer" class="dialog-footer" style="text-align: right; padding-right: 20px">
            <el-button size="mini" @click="handleCloseDialog"> 取 消 </el-button>
            <el-button size="mini" v-show="type === 'add'" type="primary" @click="handleSave">保 存 </el-button>
        </div>
    </yh-dialog>
</template>
<script lang="ts">
import { downLoadFile } from '@/utils/request';
import { dateFormat, getConfigItem, numberFormat, timeFormat } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { Component, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import UploadFileShow from './upload-file-show.vue';
import RiskTable from '@/common/components/risk-table-plus.vue';
import { ColumnVO, PageVO, TableConfigVO } from '@/common/vo';
import { FeedbackRepVO, FeedbackVO, OverrunEventVO } from '../vo/disposal-center';
import API from '../api/disposal-center';
import XEUtils from 'xe-utils';
import JSEncrypt from 'jsencrypt';

@Component({ name: 'SystemParamSetting', components: { UploadFileShow, RiskTable } })
export default class SystemParamSetting extends Vue {
    @PropSync('visible') syncVisible: boolean;
    @Prop() overrunDetail: any;
    @Prop() type: string; // add | look

    public visibleTemp: boolean = false;
    actionUrl: string = ''; // 附件上传url
    headerObj = { Authentication: getUser().sessionId }; // 上传接口请求表头
    fileList1: any[] = [
        // { name: '附件1', url: 'relativePath', fileNo: '21' },
        // { name: '名字特特特特特特特二胎长的附件2', url: 'relativePath', fileNo: '31' },
    ];

    tableLoading: boolean = false;
    tableData: FeedbackVO[] = [];
    tableConfig: TableConfigVO = {
        rowKey: 'feedbackId', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };

    compareTextPojo: any = {
        '0': '>',
        '1': '<',
        '2': '≥',
        '3': '≤',
        '4': '=',
        '5': '≠',
        '6': ' ',
    };

    columns: ColumnVO[] = [
        {
            title: '反馈时间',
            field: 'ctDate',
            align: 'center',
            width: 200,
            render: (value, row) => dateFormat(value) + ' ' + timeFormat(row.ctTime),
        },
        {
            title: '反馈方案',
            field: 'feedBackName',
            minWidth: 200,
            notShowTooltip: false,
        },
        {
            title: '附件',
            field: 'fileName',
            notShowTooltip: false,
            minWidth: 200,
        },
    ];
    paging: PageVO = { pageSize: 25, currentPage: 1, total: 0 };

    submitForm: OverrunEventVO = {
        overrunEventId: null,
        feedbackStatus: '',
        dictFundCodes: [],
        entryName: '',
        tradeDate: null,
        thresholdValue: '',
        compareType: '',
        result: null,
        ctDate: null,
        prohibitionDate: null,
        insideDays: null,
        overrunInfo: '',
        articeInfo: '',
        clauseCode: '',
        adjustProgerss: 0,
    };

    feedbackName: string = ''; // 反馈方案textarea
    rsaPassWord: any = null; // 加密
    BASE_URL_API = getConfigItem('BASE_URL_API');

    created() {}

    mounted() {
        this.actionUrl = this.BASE_URL_API + '/apiAssetFile/upload';
        this.getDetailList();
        this.getFeedbackList();
        var encryptor = new JSEncrypt(); // 创建加密对象实例
        // 之前ssl生成的公钥，复制的时候要小心不要有空格
        var pubKey =
            'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI1/pR72vGeQoQ8YxKVrDzV6RriOkNkW0UWw4JgXhH417lULhKMQWK3GeJW+Tg0kHlhpx4iQNxrEPlroCqZfylgPI+x0AohcnvkY52VGQGLnms2tMefBKdz2BHUAp7MdF7GsGtpiHWSZbEWk5onkB7pH8Q0KlNAB+7BoNTj9MOywIDAQAB';
        encryptor.setPublicKey(pubKey); // 设置公钥
        this.rsaPassWord = encryptor.encrypt('zszg@zgssfkxt'); // 对内容进行加密
    }

    @Watch('visible', { immediate: true, deep: true })
    onWatchVisible(value) {
        if (value !== this.visibleTemp) {
            this.visibleTemp = value;
        }
    }

    // @Watch('overrunDetail', { immediate: true })
    // watchOverrunDetail(newData) {
    //     if (newData) {
    //         this.submitForm = data;
    //     }
    // }

    /**
     * 获取历史反馈记录
     */
    getFeedbackList(): void {
        API.getFeedbackList({ overrunEventId: this.overrunDetail.overrunEventId, feedBackType: 2, paging: this.paging }).then((res: any) => {
            if (this.type === 'look' && res.list && res.list.length && this.paging.currentPage === 1) {
                this.feedbackName = res.list[0].feedBackName;
                let fileList = [];
                if (res.list[0].fileName) {
                    res.list[0].fileName.forEach((ele, index) => {
                        fileList.push({
                            name: ele,
                            url: '',
                            fileNo: res.list[0].fileCode[index],
                        });
                    });
                }
                this.fileList1 = fileList;
            }
            this.tableData = res.list;
            this.paging.total = res.total;
        });
    }

    getDetailList(): void {
        API.getOverrunEventDetail({ overrunEventId: this.overrunDetail.overrunEventId }).then((res: OverrunEventVO) => {
            let data = JSON.parse(JSON.stringify(res));
            data.tradeDate = dateFormat(res.tradeDate) || '--';
            data.result = numberFormat(res.result, 2) || '--';
            data.thresholdValue = this.compareTextPojo[res.compareType] + numberFormat(res.thresholdValue, 2) || '--';
            data.ctDate = dateFormat(res.ctDate) || '--';
            this.submitForm = data;
        });
    }

    /**
     * 保存事件
     */
    handleSave(): void {
        if (!this.verify()) return;
        this.$emit('initFeedback', {
            feedbackName: this.feedbackName,
            fileCode: this.fileList1.map(o => o.fileNo),
            fileName: this.fileList1.map(o => o.name),
            overrunEventId: this.overrunDetail.overrunEventId,
            feedbackType: '2',
        });
    }

    /**
     * 关闭dialog事件
     */
    handleCloseDialog(): void {
        this.syncVisible = false;
    }

    verify() {
        if (!this.overrunDetail.overrunEventId) {
            this.yh_message_warn('事件编号不能为空!');
            return false;
        }
        if (!this.feedbackName.trim()) {
            this.yh_message_warn('反馈方案不能为空!');
            return false;
        }
        return true;
    }

    /**
     * 附件单元格点击事件
     */
    handleCellFile(name, code): void {
        console.log('current:: fileCode:', code);

        downLoadFile({
            url: '/apiAssetFile/downLoad',
            method: 'post',
            data: { fileId: [code], fileName: name, passWord: this.rsaPassWord },
        });
    }

    // 文件上传
    uploadFileSuccess(res, file, fileList, type) {
        console.log('文件上传', res);
        if (res.returnMsg && res.returnMsg !== 'SUCCESS') {
            this.$message.warning(res.returnMsg);
            return;
        }
        this.fileList1.push({
            name: res.data.fileName,
            // url: res.data.relativePath,
            fileNo: res.data.fileId,
        });
    }

    uploadFileError(res, file, fileList, type) {
        this.$message.warning('文件格式不支持!');
    }

    // 下载文件
    downLoadFileBtn(param) {
        downLoadFile({
            url: '/apiAssetFile/downLoad',
            method: 'post',
            data: { fileId: [param.fileNo], fileName: param.name, passWord: this.rsaPassWord },
        });
    }

    // 删除已上传文件
    confirmDelFile1(param) {
        this.fileList1.forEach((item, index) => {
            if (item.fileNo == param.fileNo) {
                this.fileList1.splice(index, 1);
            }
        });
    }

    // 格式化产品代码
    private formatDictFundCodes(cellValue): string {
        let valueStr = XEUtils.map(cellValue, item => {
            if (item) {
                return item.dictKey + '-' + item.dictKeyName;
            } else {
                return '--';
            }
        });
        return valueStr.toString();
    }

    beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 10;

        // if (!isJPG) {
        //     this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
            this.yh_message_warn('上传大小不能超过 10MB!');
        }
        return isLt2M;
    }

    /**
     * 连续超限天数 tag样式设置
     */
    handleTagStyle(value) {
        if (value <= 5) {
            return 'tag1';
        } else if (value < 10 && value > 5) {
            return 'tag2';
        } else if (value >= 10) {
            return 'tag3';
        } else {
            return 'tag-d';
        }
    }
}
</script>
<style lang="scss" scoped>
.table {
    border-top: 1px solid rgba(239, 239, 239, 1);
    .el-row {
        border-right: 1px solid rgba(239, 239, 239, 1);
        display: flex;
        .el-col {
            border: 1px solid rgba(239, 239, 239, 1);
            border-top: none;
            border-right: none;
            padding: 5px 5px;
            min-height: 32px;
            font-size: 12px;
            display: flex;
            align-items: center;
        }
        .el-col-5 {
            justify-content: center;
            background: #f7f8fc;
        }
        .el-col-7,
        .el-col-19 {
            padding-left: 10px;
        }
    }

    .textarea {
        .el-col {
            min-height: 85px;
        }
        .el-col-5 {
            flex-direction: column;
        }
    }
}
.title {
    margin: 15px 10px 10px 0;
    display: flex;
    align-items: center;
    font-weight: 600;
}

// .title::before {
//     display: inline-block;
//     content: '';
//     width: 2px;
//     height: 20px;
//     background: #409eff;
//     margin-right: 10px;
// }

a {
    color: #578bec;
    padding: 0 5px;
}

/* 附件链接 */
/deep/ .vxe-table .vxe-body--column .vxe-cell {
    height: auto;
    line-height: inherit;
}

.tag1,
.tag2,
.tag3,
.tag4,
.tag-d {
    color: #fff;
    width: 30px;
    text-align: center;
}
.tag1 {
    background-color: #fff0d9;
    color: rgb(255, 178, 64);
}
.tag2 {
    background-color: #fbe4cc;
    color: rgb(237, 120, 0);
}
.tag3 {
    background-color: #fadbd4;
    color: rgb(231, 77, 40);
}
.tag4 {
    background-color: #f1e9e2;
    color: rgb(187, 145, 111);
}

/deep/ .el-upload {
    .el-button {
        border: 1px solid #dcdfe6;
    }
    .el-button--small {
        height: 28px;

        i,
        span {
            font-size: 12px !important;
        }
    }
}
</style>
